package com.example.petcare.controller.admin;

import com.example.petcare.pojo.*;
import com.example.petcare.service.AdminService;
import com.example.petcare.service.HostService;
import com.example.petcare.service.ProviderService;
import com.example.petcare.utils.JwtUtil;
import com.example.petcare.utils.Md5Util;
import com.example.petcare.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController//标记为控制器类,并且返回json数据
@RequestMapping("/admin")//请求路径
@Slf4j
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private ProviderService providerService;

    @Autowired
    private HostService hostService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;// 注入redis模板

    // 登录
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {

        // 根据用户名查询用户
        Provider loginAdmin = providerService.findByUsername(username);

        // 判断该用户是否存在
        if (loginAdmin == null) {
            return Result.error("用户名不存在");
        }


        // 判断密码是否正确     loginuser对象中的密码是密文
        if (Md5Util.getMD5String(password).equals(loginAdmin.getPassword())) {

            // 登录成功,生成jwt token令牌
            Map<String,Object> claims = new HashMap<>();// 创建一个map集合
            claims.put("AdminId",loginAdmin.getProviderId());// 将用户id和用户名放入map集合
            claims.put("username",loginAdmin.getUsername());

            String role = "admin";
            // 把role存入ThreadLocal
            ThreadLocalUtil.setRole(role);
            log.info("这是AdminController中的role:{}",ThreadLocalUtil.getRole());

            String token = JwtUtil.genToken(claims,role);// 生成jwt token令牌

            // 把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,365, TimeUnit.DAYS);// 把token既作为键，又作为值存进去

            return Result.success(token);// 返回token
        }

        return Result.error("密码错误");
    }


    // 查询服务商审核列表（分页查询）
    @GetMapping("/provider/list")
    public Result<PageBean<Provider>> list(Integer pageNum, Integer pageSize)
    {
        PageBean<Provider> pb= adminService.list(pageNum, pageSize);
        return Result.success(pb);
    }

    // 审核不通过（更新rejectStatus）
    @PutMapping("/provider/reject")
    public Result reject(@RequestParam("providerId") Integer providerId) {
        adminService.reject(providerId);
        return Result.success();
    }

    // 审核通过（更新providerStatus）
    @PutMapping("/provider/pass")
    public Result pass(@RequestParam("providerId") int providerId) {
        adminService.pass(providerId);
        return Result.success();
    }

    // 更新密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params, @RequestHeader("Authorization") String token){

        // @RequestHeader("Authorization")  String token
        // token是浏览器通过请求头的方式携带过来的,请求头的名字叫Authorization

        // 1.校验参数
        String oldPwd = params.get("old_pwd");// 获取旧密码
        String newPwd = params.get("new_pwd");// 获取新密码
        String rePwd = params.get("re_pwd");// 获取确认密码

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }

        // 新密码不能和旧密码一样
        if (oldPwd.equals(newPwd)){
            return Result.error("新密码不能和旧密码一样");
        }

        // 原密码是否正确
        // 调用providerService根据用户名拿到原密码，再和old_Pwd比对
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Provider loginProvider= providerService.findByUsername(username);
        if(!loginProvider.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码错误");
        }

        // 新密码和确认密码是否一致,即newPwd和rePwd是否相等
        if (!newPwd.equals(rePwd)){
            return Result.error("两次填写的新密码不一致");
        }

        // 2.调用service完成密码更新
        providerService.updatePwd(newPwd);
        System.out.println("新密码是"+newPwd);

        // 删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);

        return Result.success();

    }


    // 更新基本信息
    @PutMapping("/update")
    public Result update(@RequestBody @Validated Provider provider){
        providerService.update(provider);// 更新用户信息
        return Result.success();// 返回成功
    }

    // 获取当前登录用户信息
    @GetMapping("/info")
    public Result<Provider> adminInfo(){
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");// 获取用户名
        Provider provider = providerService.findByUsername(username);// 根据用户名查询用户,返回用户对象
        return Result.success(provider);// 返回用户对象
    }



    // 查询用户列表
    @GetMapping("/userlist")
    public Result<PageBean<User>> userList(Integer pageNum, Integer pageSize) {
        PageBean<User> pb = adminService.userList(pageNum, pageSize);
        return Result.success(pb);
    }

    // 用户审核通过
    @PostMapping("/user/pass")
    public Result userPass(@RequestParam("userId") Integer userId) {
        adminService.userPass(userId);
        return Result.success();
    }

    // 用户审核不通过
    @PostMapping("/user/reject")
    public Result userReject(@RequestParam("userId") Integer userId) {

        adminService.userReject(userId);

        return Result.success();
    }

    // 商品审核通过
    @PostMapping("/goods/pass")
    public Result goodsPass(@RequestParam("gId") Integer gId) {
        adminService.goodsPass(gId);
        return Result.success();
    }

    // 商品审核不通过
    @PostMapping("/goods/reject")
    public Result goodsReject(@RequestParam("gId") Integer gId) {
        adminService.goodsReject(gId);
        return Result.success();
    }

    // 添加审核意见（商品），并且审核不通过
    @PostMapping("/goods/auditComment")
    public Result addAuditComment(@RequestParam("gId") Integer gId, @RequestParam("auditComment") String auditComment) {
        // 调用service方法添加审核意见
        adminService.addAuditComment(gId, auditComment);
        return Result.success();
    }

    // 获取所有待审核的商品列表(条件分页查询),根据上下架，价格和商家ID
    @GetMapping("/goods/list")
    public Result<PageBean<Goods>> getGoodsList(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(value = "isOnSale", required = false) Boolean isOnSale,
            @RequestParam(value = "price", required = false) Double price,
            @RequestParam(value = "providerId", required = false) Integer providerId



    ) {
        PageBean<Goods> pb = adminService.getGoodsList(pageNum, pageSize, isOnSale, price, providerId);
        return Result.success(pb);
    }


    // 查看用户宠物列表，不用分页
    @GetMapping("/petlist")
    public Result<List<Pet>> listPet(@RequestParam("userId") Integer userId) {
        List<Pet> pets = adminService.petlist(userId);
        return Result.success(pets);
    }


    // 查询所有已经审核过的商家的具体信息，从provider表中查询
    @GetMapping("/provider")
    public Result<List<Provider>> listProvider() {
        List<Provider> list = hostService.listProvider();
        return Result.success(list);
    }


}
